import Vue from 'vue'
import { getInfo, login, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    authorities: [],
    companyId: '',
    avatar: '',
    userId: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_SUPERADMIN: (state, superAdmin) => {
      state.superAdmin = superAdmin
    },
    SET_AUTHORITIES: (state, authorities) => {
      state.authorities = authorities
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_COMPANYID: (state, companyId) => {
      state.companyId = companyId
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          
          const result = response.data
          const token = result.access_token
          Vue.ls.set(ACCESS_TOKEN, token, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.data
          console.info('获取用户信息',result)
          const access = []
          if (result.authorities) {
            result.authorities.map(item => {
              if (item.authority) {
                access.push(item.authority)
              }
            })
          }
          commit('SET_ROLES', ['admin'])
          // 转换权限
          commit('SET_AUTHORITIES', access)
          commit('SET_INFO', result)
          commit('SET_AVATAR', '/avatar.jpg')
          commit('SET_SUPERADMIN', result.superAdmin)
          commit('SET_COMPANYID', result.companyId)
          commit('SET_USERID', result.userId)
          commit('SET_NAME', { name: result.nickName, welcome: welcome() })
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          Vue.ls.remove(ACCESS_TOKEN)
        })
      })
    }

  }
}

export default user
